import React, {Component} from 'react';
import qs from 'qs';
import { AMapScene,PointLayer,LoadImage,LayerEvent} from '@antv/l7-react';
import img1 from './img/airport1.svg';
import img2 from './img/airport2.svg';
import img3 from './img/airport3.svg';
import {Table,Drawer,Descriptions,List,Button} from "antd";
import axios from 'axios';
import {Chart} from "_@antv_g2@4.2.5@@antv/g2";
import { Input } from 'antd';
import Highlighter from 'react-highlight-words';
import { Icon } from '@ant-design/compatible';
import {  Util } from '@antv/g2';
class Demo3 extends React.Component {
    
    state={
        data:[],
        visible:false,
        loading:false,
        model:[],//飞机机型数据
        quantity:[],//飞机数量数据
        Usage:[],//飞机使用时间数据
        currentAptCname:'', //机场名字
        currentAirPort:{}, //机场数据
        currentFlightData:[], //当页显示的航班数据
        pagination:{  //分页器：当前页码、每页显示的条数、总条目数
            current: 1, //当前页码
            pageSize:5, //每页显示的条数
            total:0, //总条目数
        },
        searchText: '',//筛选框 
        searchedColumn: '',//筛选框
        
    }
    //点击机场图标
    handleClick = (e)=>{
        this.setState({
            loading: true,
            currentAirPort:e.feature,
            currentAptCname: e.feature.aptCname,
            visible: true,
            pagination: {
              current: 1,
              pageSize: 5,
              total: 0,
            },
          },
          () => {
            const { currentAptCname, pagination } = this.state;
            const url = `http://flightapi.xiexianbo.xin/flight/getForg?fdstAptCname=${currentAptCname}&pageSize=${pagination.pageSize}`;
            fetch(url)
              .then((response) => response.json())
              .then((res) => {
                this.setState({
                  currentFlightData: res.data.data,
                  loading: false,
                  pagination: {
                    ...this.state.pagination,
                    total: res.data.total,
                  },
                });
                // console.log(this.state.pagination);
              });
          }
        );
    };
    //分页器改变
    handleTableChange=(newPagination)=>{
        console.log(newPagination);
        this.setState({
          pagination: {
            ...this.state.pagination,
            ...newPagination,
          },
        },()=>{
        const {currentAptCname,pagination}=this.state
        const url = `http://flightapi.xiexianbo.xin/flight/getForg?fdstAptCname=${currentAptCname}&pageSize=${pagination.pageSize}&pageNo=${pagination.current}`;
        fetch(url)
            .then(response => response.json())
            .then(res => {
                this.setState({
                    currentFlightData:res.data.data,
                })
            });
        });
    }
    //关闭Drawer
    onClose = () => {
        this.setState({
          visible: false,
        });
      };
    //关闭Drawer2
    onCloses = () => {
      this.setState({
        visible: false,
      });
    };
      //加载机场数据
    componentDidMount(){
      this.modeldate()
      this.quantitydate()
      this.Usagedate()
        const url = 'http://flightapi.xiexianbo.xin/airPort/listAll';
        fetch(url)
            .then(response => response.json())
            .then(res => {
                this.setState({
                    data:res.data.data
                })
            });
      }
    
    //各个机型数量柱形图
    // drawFight(){
    //     const url = 'http://flightapi.xiexianbo.xin/flight/getTopAT';
    //     fetch(url)
    //         .then(response => response.json())
    //         .then(res => {
    //             this.setState({
    //                 fight:res.data.data
    //             })
    //         });
    // }

    modeldate=async ()=>{
      const r= await axios.get('http://flightapi.xiexianbo.xin/flight/getTopAT')
      this.setState({
              model:r.data.data.data,
          }
      )
  }

  //各航空公司的飞机数量条形图数据
  quantitydate=async ()=>{
    const r= await axios.get('http://flightapi.xiexianbo.xin/flight/getComAirNum')
    this.setState({
            quantity:r.data.data.data,
        }
    )
}
  //各航空公司的飞机使用的平均时间饼图数据
  Usagedate=async ()=>{
    const r= await axios.get('http://flightapi.xiexianbo.xin/flight/getAirAVGAge')
    this.setState({
            Usage:r.data.data.data,
        }
    )
}

    //各个机型数量柱形图
    drawFightColumn=()=>{
        const chart = new  Chart({
            container: 'container',
            // autoFit: true,
            height: 400,
            width: 600,
        });
        chart.data(this.state.model);
        chart.scale('flightAmount', {
            nice: true,
        });
        chart.tooltip({
            showMarkers: false,
            shared: true,
        });

        chart
            .interval()//间隔
            .position('atype*flightAmount')//n:1映射
            .color('atype')
            .adjust([
                {
                    type: 'dodge',
                    marginRatio: 0,
                },
            ]);//数据调整4种


        chart.interaction('active-region');//4种交互类型，高亮
        chart.render();
    }

    //各航空公司的飞机数量条形图
    drawFightBar=()=>{
      const chart = new Chart({
          container: 'containers',
          // autoFit: true,
          height: 600,
          width:600,
      });
      chart.data(this.state.quantity);
      chart.scale({
          value: {
              max: 400000,
              min: 0,
          },
      });
      chart.tooltip({
        showMarkers: false,
        shared: true,
    });
      chart.axis('airCName', {
          title: null,
          tickLine: null,
          line: null,
      });
      chart.legend(false);
      chart.coordinate().transpose();//坐标倒置
      chart
          .interval()
          .position('airCName*airNumber')
          .color('airCName')
          .size(26)
          .label('airNumber', {
              style: {
                  fill: '#8d8d8d',
              },
              offset: 10,
          });
      chart.interaction('element-active');
      chart.render();
  }

  //各个公司的飞机使用的平均时间饼图
  drawFightPie=()=>{
    const chart = new Chart({
      container: 'containerss',
      // autoFit: true,
      height: 350,
      width:600,
    });
    chart.data(this.state.Usage);
    
    chart.coordinate('theta', {
      radius: 0.75
    });
    chart.tooltip({
      showMarkers: false
    });
    
    chart
      .interval()
      .adjust('stack')//数据调整方式
      .position('airAgeAvg')
      .color('airCName')
      .style({ opacity: 0.4 })
      .state({
        active: {
          style: (element) => {
            const shape = element.shape;
            return {
              matrix: Util.zoom(shape, 1.1),
            }
          }
        }
      })
      // .label('airCName', (val) => {
      //   const opacity = val === '四线及以下' ? 1 : 0.5;
      //   return {
      //     offset: -30,
      //     style: {
      //       opacity,
      //       fill: 'white',
      //       fontSize: 12,
      //       shadowBlur: 2,
      //       shadowColor: 'rgba(0, 0, 0, .45)',
      //     },
      //     content: (obj) => {
      //       return obj.type + '\n' + obj.value + '%';
      //     },
      //   };
      // });
    
    chart.interaction('element-single-selected');
    
    chart.render();
  }

    //筛选操作函数
    getColumnSearchProps = dataIndex => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
          <div style={{ padding: 8 }}>
            <Input
              ref={node => {
                this.searchInput = node;
              }}
              placeholder={`Search ${dataIndex}`}
              value={selectedKeys[0]}
              onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
              style={{ width: 188, marginBottom: 8, display: 'block' }}
            />
            <Button
              type="primary"
              onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
              icon="search"
              size="small"
              style={{ width: 90, marginRight: 8 }}
            >
              Search
            </Button>
            <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
              Reset
            </Button>
          </div>
        ),
        filterIcon: filtered => (
          <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
        ),
        onFilter: (value, record) =>
          record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => this.searchInput.select());
          }
        },
        render: text =>
          this.state.searchedColumn === dataIndex ? (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[this.state.searchText]}
              autoEscape
              textToHighlight={text.toString()}
            />
          ) : (
            text
          ),
      });
    
      handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        this.setState({
          searchText: selectedKeys[0],
          searchedColumn: dataIndex,
        });
      };
    
      handleReset = clearFilters => {
        clearFilters();
        this.setState({ searchText: '' });
      };



    render(){
        const columns = [
            {
              title: '航空公司',
              dataIndex: 'airCName',
              key: 'airCName',
              width: '30%',
              ...this.getColumnSearchProps('airCName'),
            },
            {
                title: 'ID',
                dataIndex: 'id',
                key: 'id',
                defaultSortOrder: 'descend',
                sorter: (a, b) => a.id - b.id,
                width: '20%',
                ...this.getColumnSearchProps('id'),
              },
            {
                title: '起飞时间',
                dataIndex: 'scheduledDeptime',
                key: 'scheduledDeptime',
            },
            {
              title: '到达时间',
              dataIndex: 'scheduledArrtime',
              key: 'scheduledArrtime',
            },
        ]
        return (
            <>
                <AMapScene
                    option={{}}
                    map={{
                        center: [110.19382669582967, 50.258134],
                        pitch: 0,
                        style: 'light',
                        zoom: 3.5,
                        rotation :0,
                    }}
                    
                    style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                    }}
                >
                    <LoadImage  name="00" url= {img1}/>
                    <LoadImage  name="11" url= {img2}/>
                    <LoadImage  name="01" url= {img3}/>
                    
                    <PointLayer
                        key={'2'}
                        aotoFit={true}
                        source={{
                            data:this.state.data,
                            parser:{
                                type:"json",
                                x:'longitude',
                                y:'latitude',
                            },

                        }}
                        shape={{
                            field:'flightNumber',
                            values: (flightNumber)=>{
                                if(flightNumber > 1000){
                                    return '11'
                                }else if(flightNumber===0){
                                    return '01'
                                }
                                else{
                                    return '00'
                                }
                                    
                            },
                        }}
                        style={{
                            opacity: 1,
                        }}
                        active={{
                            option: {
                                color: 'red',
                            },
                        }}
                    >
                    <LayerEvent type="click" handler={this.handleClick}/>


                    </PointLayer>
                </AMapScene>
                <Drawer
                    title="机场数据"
                    placement="right"
                    size="large"
                    closable={true}
                    onClose={this.onClose}
                    visible={this.state.visible}
                >
                <Descriptions title="机场信息" column={1} size='small'bordered>
                <Descriptions.Item label="IATACode">{this.state.currentAirPort.IATACode}</Descriptions.Item>
                {/* <Descriptions.Item label="航班号">{this.state.currentAirPort.flightNumber}</Descriptions.Item> */}
                <Descriptions.Item label="机场城市">{this.state.currentAirPort.aptCcity}</Descriptions.Item>
                <Descriptions.Item label="机场名称">{this.state.currentAirPort.aptCname}</Descriptions.Item>
                </Descriptions> 
                <Table
                columns={columns}
                rowKey={record=>record.num}
                dataSource={this.state.currentFlightData}
                pagination={this.state.pagination}
                loading={this.state.loading}
                onChange={this.handleTableChange}
                expandedRowRender={record => <p style={{ margin: 0 }}>航班号: {record.fnum}</p>}              />
                
                {/* <div id="container" className="drawFightColumn">
                    <Button type="primary" onClick={this.drawFightColumn} >柱形图</Button>
                </div> */}
                <div id="container">
                  <Button type="primary" onClick={this.drawFightColumn} >飞机机型</Button>
                </div>
                <div id="containers">
                  <Button type="primary" onClick={this.drawFightBar} >飞机数量</Button>
                </div>
                <div id="containerss">
                  <Button type="primary" onClick={this.drawFightPie} >飞机年龄</Button>
                </div>
                </Drawer>

                {/* <Drawer
                title="柱形图"
                placement="left"
                closable={false}
                onClose={this.onCloses}
                visible={this.state.visible}
                >
                    <div>
                        <div id="container">
                            <Button type="primary" onClick={this.drawFightColumn} >飞机机型</Button>
                        </div>
                    </div>
                </Drawer> */}
            </>
        )
    }
} 

export default Demo3;
 